﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using Looptribe.Moodlin8.Model;

namespace Looptribe.Moodlin8.ViewModel
{
    public class NextAssignmentsViewModel : LoadingViewModel
    {
        public ICommand GotoAssignmentCommand { get; set; }

        private Course _course;

        private readonly ObservableCollection<AssignmentWrapper> _assignments = new ObservableCollection<AssignmentWrapper>();
        public ObservableCollection<AssignmentWrapper> Assignments
        {
            get { return _assignments; }
        }

        public NextAssignmentsViewModel()
        {
            GotoAssignmentCommand = new RelayCommand<AssignmentWrapper>(ExecuteGotoAssignment);
        }

        private void ExecuteGotoAssignment(AssignmentWrapper assignment)
        {
            RunAsync(() => Controller.GotoAssignment(assignment));
        }

        public async void LoadContent(Course course)
        {
            _course = course;
            await Refresh();
        }

        public async override Task Refresh()
        {
            IsLoading = true;
            Assignments.Clear();
            var courses = _course != null ? new [] { _course } : (await Api.GetEnrolledCoursesAsync(CurrentUser)).Data;
            var assignments = (await Api.GetAssignmentsAsync(_course == null ? null : new[] { _course.Id })).Data;
            IsLoading = false;

            if (assignments != null)
            {
                var filtered = assignments.
                    Where(a => a.DueDate.HasValue && a.DueDate > DateTime.Now).
                    Where(a => a.Grades.Items.Count == 0 ||
                        (a.Grades.Items.SelectMany(gradeItem => gradeItem.Grades).All(grade => !grade.Grade.HasValue && !grade.DateGraded.HasValue))).
                    OrderBy(a => a.DueDate.HasValue ? a.DueDate.Value : DateTime.MaxValue);
                foreach (var wrapper in filtered.Select(a => new AssignmentWrapper(a, courses.FirstOrDefault(c => c.Id == a.Course))))
                    Assignments.Add(wrapper);
            }
        }
    }
}
